//
//  CustomAlertView.m
//  Tool
//
//  Created by flychi on 15/12/17.
//  Copyright © 2015年 Mike. All rights reserved.
//

static const float TITLE_FONT_SIZE  = 18.0f;
static const float MESSAGE_FONT_SIZE  = 15.0f;
static const float BUTTON_FONT_SIZE  = 15.0f;
static const float MARGIN_TOP  = 20.0f;
static const float MARGIN_LEFT_LARGE  = 30.0f;
static const float MARGIN_LEFT_SMALL  = 15.0f;
static const float MARGIN_RIGHT_LARGE  = 30.0f;
static const float MARGIN_RIGHT_SMALL  = 15.0f;
static const float SPACE_LARGE  = 30.0f;
static const float SPACE_SMALL  = 5.0f;
static const float MESSAGE_LINE_SPACE  = 5.0f;

//#define RGBA(R, G, B, A) [UIColor colorWithRed:R / 255.0 green:G / 255.0 blue:B / 255.0 alpha:A]

#import "AlertView.h"

@interface AlertView ()

@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UIImage *icon;
@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSString *message;


@property (strong, nonatomic) UIView *backgroundView;

@property (strong, nonatomic) UIView *titleView;

@property (strong, nonatomic) UIImageView *iconImageView;

@property (strong, nonatomic) UILabel *titleLabel;

@property (strong, nonatomic) UILabel *messageLabel;

@property (strong, nonatomic) NSMutableArray *buttonArray;

@property (strong, nonatomic) NSMutableArray *buttonTitleArray;

//@property(copy,nonatomic)void (^cancelBlock)();
//@property(copy,nonatomic)void (^confirmBlock)();
@property(copy,nonatomic)void (^clickBlock)(NSInteger index);

- (void)setTitleColor:(UIColor *)color fontSize:(CGFloat)size;

- (void)setMessageColor:(UIColor *)color fontSize:(CGFloat)size;

- (void)setButtonTitleColor:(UIColor *)color fontSize:(CGFloat)size atIndex:(NSInteger)index;

- (void)show;

- (void)hide;

@end

CGFloat contentViewWidths;
CGFloat contentViewHeights;

@implementation AlertView

+ (void)alertWithTitle:(NSString *)title
                  icon:(UIImage *)icon
               message:(NSString *)message
            clickBlock:(void (^)(NSInteger index))clickBlock
          buttonTitles:(NSString *)buttonTitles, ... NS_REQUIRES_NIL_TERMINATION{
    AlertView *alertView=[[AlertView alloc]initWithTitle:title icon:icon message:message clickBlock:clickBlock buttonTitles:buttonTitles, nil];
    [alertView show];
}

+ (void)alertWithTitle:(NSString *)title
               message:(NSString *)message
            clickBlock:(void (^)(NSInteger index))clickBlock
          buttonTitles:(NSString *)buttonTitles, ... NS_REQUIRES_NIL_TERMINATION{
    [AlertView alertWithTitle:title icon:nil message:message clickBlock:clickBlock buttonTitles:buttonTitles, nil];
}

+ (void)alertWithTitle:(NSString *)title
                  icon:(UIImage *)icon
               message:(NSString *)message
           cancelTitle:(NSString *)cancelTitle
           cancelBlock:(void (^)())cancelblock
          confirmTitle:(NSString *)confirmTitle
          confrimBlock:(void (^)())confirmBlock{
    AlertView *alertView=[[AlertView alloc]initWithTitle:title icon:icon message:message clickBlock:^(NSInteger index) {
        if (index==1) {
            if (cancelblock) {
                cancelblock();
            }
        }else{
            if (confirmBlock) {
                confirmBlock();
            }
        }
    } buttonTitles:cancelTitle, confirmTitle, nil];
    [alertView show];
}

+ (void)alertWithTitle:(NSString *)title
               message:(NSString *)message
           cancelTitle:(NSString *)cancelTitle
           cancelBlock:(void (^)())cancelblock
          confirmTitle:(NSString *)confirmTitle
          confrimBlock:(void (^)())confirmBlock{
    [AlertView alertWithTitle:title icon:nil message:message cancelTitle:cancelTitle cancelBlock:cancelblock confirmTitle:confirmTitle confrimBlock:confirmBlock];
}

+ (void)alertWithTitle:(NSString *)title
               message:(NSString *)message
           buttonTitle:(NSString *)buttonTitle
          confrimBlock:(void (^)())confirmBlock{
    AlertView *alertView=[[AlertView alloc]initWithTitle:title icon:nil message:message clickBlock:^(NSInteger index) {
        if (confirmBlock) {
            confirmBlock();
        }
    } buttonTitles:buttonTitle,nil];
  
    [alertView show];

}

+ (void)alertWithTitle:(NSString *)title
               message:(NSString *)message
           buttonTitle:(NSString *)buttonTitle{
    [AlertView alertWithTitle:title message:message buttonTitle:buttonTitle confrimBlock:nil];
}

+ (void)alertWithTitle:(NSString *)title
               message:(NSString *)message{
     [AlertView alertWithTitle:title message:message buttonTitle:nil confrimBlock:nil];
}

- (instancetype)initWithTitle:(NSString *)title
                         icon:(UIImage *)icon
                      message:(NSString *)message
                   clickBlock:(void (^)(NSInteger index))clickBlock
                 buttonTitles:(NSString *)buttonTitles, ...{
    if (self = [super initWithFrame:[UIScreen mainScreen].bounds]) {
        _clickBlock=[clickBlock copy];
        _icon = icon;
        _title = title;
        _message = message;
        _buttonArray = [NSMutableArray array];
        _buttonTitleArray = [NSMutableArray array];
        
        va_list args;
        va_start(args, buttonTitles);
        if (buttonTitles)
        {
            [_buttonTitleArray addObject:buttonTitles];
            while (1)
            {
                NSString *  otherButtonTitle = va_arg(args, NSString *);
                if(otherButtonTitle == nil) {
                    break;
                } else {
                    [_buttonTitleArray addObject:otherButtonTitle];
                }
            }
        }
        va_end(args);
        
        self.backgroundColor = [UIColor clearColor];
        _backgroundView = [[UIView alloc] initWithFrame:self.frame];
        _backgroundView.backgroundColor = [UIColor blackColor];
        [self addSubview:_backgroundView];
        [self initContentView];
    }
    return self;
}

// Init the content of content view
- (void)initContentView {
    contentViewWidths = 240* self.frame.size.width / 320;
    contentViewHeights = MARGIN_TOP;
    
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = [UIColor whiteColor];
    _contentView.layer.cornerRadius = 5.0;
    _contentView.layer.masksToBounds = YES;
    
    [self initTitleAndIcon];
    [self initMessage];
    [self initAllButtons];
    
    _contentView.frame = CGRectMake(0, 0, contentViewWidths, contentViewHeights);
    _contentView.center = self.center;
    [self addSubview:_contentView];
}

- (void)initTitleAndIcon {
    _titleView = [[UIView alloc] init];
    if (_icon != nil) {
        _iconImageView = [[UIImageView alloc] init];
        _iconImageView.image = _icon;
        _iconImageView.frame = CGRectMake(0, 0, 20, 20);
        [_titleView addSubview:_iconImageView];
    }
    
//    CGSize titleSize = [self getTitleSize];
    if (_title != nil && ![_title isEqualToString:@""]) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.text = _title;
        _titleLabel.textColor = [UIColor colorWithHexString:@"333333"];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:TITLE_FONT_SIZE];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.numberOfLines = 0;
        _titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        _titleLabel.frame = CGRectMake(0, 0, contentViewWidths, 45);
        [_titleView addSubview:_titleLabel];
    }
    _titleView.frame = CGRectMake(0, 0, contentViewWidths, 45);
    _titleView.center = CGPointMake(contentViewWidths / 2, _titleView.frame.size.height / 2);
    _titleView.backgroundColor = [UIColor whiteColor];
    
    UIView *horizontalSeperatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, contentViewWidths, 1)];
    horizontalSeperatorView.backgroundColor = [UIColor colorWithHexString:@"e1e1e1"];
    [_titleView addSubview:horizontalSeperatorView];

    [_contentView addSubview:_titleView];
    contentViewHeights += _titleView.frame.size.height;
}


// Init the message
- (void)initMessage {
    if (_message != nil) {
        _messageLabel = [[UILabel alloc] init];
        _messageLabel.text = _message;
        _messageLabel.textColor = [UIColor colorWithHexString:@"666666"];
        _messageLabel.numberOfLines = 0;
        _messageLabel.font = [UIFont systemFontOfSize:MESSAGE_FONT_SIZE];
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineSpacing = MESSAGE_LINE_SPACE;
        NSDictionary *attributes = @{NSParagraphStyleAttributeName:paragraphStyle};
        _messageLabel.attributedText = [[NSAttributedString alloc]initWithString:_message attributes:attributes];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        
        CGSize messageSize = [self getMessageSize];
        _messageLabel.frame = CGRectMake(MARGIN_LEFT_LARGE, _titleView.frame.origin.y + _titleView.frame.size.height + SPACE_LARGE, MAX(contentViewWidths - MARGIN_LEFT_LARGE - MARGIN_RIGHT_LARGE, messageSize.width), messageSize.height);
        [_contentView addSubview:_messageLabel];
        contentViewHeights += SPACE_LARGE + _messageLabel.frame.size.height;
    }
}

- (void)initAllButtons {
    
    if(_buttonTitleArray.count == 1){
        contentViewHeights +=  55;
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake( 0, _messageLabel.frame.origin.y + _messageLabel.frame.size.height + SPACE_LARGE, contentViewWidths, 45)];
        button.tag = 0;
        button.backgroundColor = [UIColor whiteColor];
        button.titleLabel.font = [UIFont systemFontOfSize:BUTTON_FONT_SIZE];
        [button setTitle:_buttonTitleArray[0] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"f49f18"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonWithPressed:) forControlEvents:UIControlEventTouchUpInside];
        [_buttonArray addObject:button];
        [_contentView addSubview:button];
    }
    else if (_buttonTitleArray.count > 1) {
        contentViewHeights +=  55;
        CGFloat buttonWidth = contentViewWidths / _buttonTitleArray.count;
        int i=0;
        for (NSString *buttonTitle in _buttonTitleArray) {
            i++;
            NSInteger index = [_buttonTitleArray indexOfObject:buttonTitle];
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(index * buttonWidth, _messageLabel.frame.origin.y + _messageLabel.frame.size.height + SPACE_LARGE, buttonWidth, 45)];
            button.tag = i;
            button.backgroundColor = [UIColor whiteColor];
            button.titleLabel.font = [UIFont systemFontOfSize:BUTTON_FONT_SIZE];
            [button setTitle:buttonTitle forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithHexString:@"f49f18"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(buttonWithPressed:) forControlEvents:UIControlEventTouchUpInside];
            [_buttonArray addObject:button];
            [_contentView addSubview:button];
        }
        
        UIView *verticalSeperatorView = [[UIView alloc] initWithFrame:CGRectMake(contentViewWidths/2, _messageLabel.frame.origin.y  + _messageLabel.frame.size.height + SPACE_LARGE + 10 , 1, 25)];
        verticalSeperatorView.backgroundColor = [UIColor colorWithHexString:@"e1e1e1"];
        [_contentView addSubview:verticalSeperatorView];
    }
    UIView *horizontalSeperatorView = [[UIView alloc] initWithFrame:CGRectMake(0, _messageLabel.frame.origin.y  + _messageLabel.frame.size.height + SPACE_LARGE, contentViewWidths, 1)];
    horizontalSeperatorView.backgroundColor = [UIColor colorWithHexString:@"e1e1e1"];
    [_contentView addSubview:horizontalSeperatorView];

}

// Get the size fo title
- (CGSize)getTitleSize {
    UIFont *font = [UIFont systemFontOfSize:TITLE_FONT_SIZE];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    CGSize size = [_title boundingRectWithSize:CGSizeMake(contentViewWidths - (MARGIN_LEFT_SMALL + MARGIN_RIGHT_SMALL + _iconImageView.frame.size.width + SPACE_SMALL), 2000)
                                       options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:attributes context:nil].size;
    
    size.width = ceil(size.width);
    size.height = ceil(size.height);
    
    return size;
}

// Get the size of message
- (CGSize)getMessageSize {
    UIFont *font = [UIFont systemFontOfSize:MESSAGE_FONT_SIZE];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = MESSAGE_LINE_SPACE;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    CGSize size = [_message boundingRectWithSize:CGSizeMake(contentViewWidths - (MARGIN_LEFT_LARGE + MARGIN_RIGHT_LARGE), 2000)
                                         options:NSStringDrawingUsesLineFragmentOrigin
                                      attributes:attributes context:nil].size;
    
    size.width = ceil(size.width);
    size.height = ceil(size.height);
    
    return size;
}

- (void)buttonWithPressed:(UIButton *)button {
    _clickBlock(button.tag);
    [self hide];
}

- (void)show {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    NSArray *windowViews = [window subviews];
    if(windowViews && [windowViews count] > 0){
        UIView *subView = [windowViews objectAtIndex:[windowViews count]-1];
        for(UIView *aSubView in subView.subviews)
        {
            [aSubView.layer removeAllAnimations];
        }
        [subView addSubview:self];
        [self showBackground];
        [self showAlertAnimation];
    }
    if (self.buttonTitleArray.count==0) {
        [self hide];
    }
}

- (void)hide {
    _contentView.hidden = YES;
    [self hideAlertAnimation];
    [self removeFromSuperview];
}

- (void)setTitleColor:(UIColor *)color fontSize:(CGFloat)size {
    if (color != nil) {
        _titleLabel.textColor = color;
    }
    
    if (size > 0) {
        _titleLabel.font = [UIFont systemFontOfSize:size];
    }
}

- (void)setMessageColor:(UIColor *)color fontSize:(CGFloat)size {
    if (color != nil) {
        _messageLabel.textColor = color;
    }
    
    if (size > 0) {
        _messageLabel.font = [UIFont systemFontOfSize:size];
    }
}

- (void)setButtonTitleColor:(UIColor *)color fontSize:(CGFloat)size atIndex:(NSInteger)index {
    UIButton *button = _buttonArray[index];
    if (color != nil) {
        [button setTitleColor:color forState:UIControlStateNormal];
    }
    
    if (size > 0) {
        button.titleLabel.font = [UIFont systemFontOfSize:size];
    }
}

- (void)showBackground
{
    _backgroundView.alpha = 0;
    [UIView beginAnimations:@"fadeIn" context:nil];
    [UIView setAnimationDuration:0.35];
    _backgroundView.alpha = 0.6;
    [UIView commitAnimations];
}

-(void)showAlertAnimation
{
    CAKeyframeAnimation * animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.30;
    animation.removedOnCompletion = YES;
    animation.fillMode = kCAFillModeForwards;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [_contentView.layer addAnimation:animation forKey:nil];
}

- (void)hideAlertAnimation {
    [UIView beginAnimations:@"fadeIn" context:nil];
    [UIView setAnimationDuration:0.35];
    _backgroundView.alpha = 0.0;
    [UIView commitAnimations];
}

@end
